#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <functional>
#include<arpa/inet.h>
#include "LOG.hpp"
#include "InetAddr.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};
const static int defaultsockfd = -1;
class UdpServer
{
public:
    //构造
    UdpServer(uint16_t port)
    :_sockfd(defaultsockfd)
    ,_port(port)
    ,_isrunning(false)
    {}
    void InitServer()
    {
        //创建Udp套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)//创建失败
        {
            LOG(FATAL,"socket error,%s,%d\n",strerror(errno),errno);
            exit(SOCKET_ERROR);
        }
        //创建成功
        LOG(INFO,"socket creat success,sockfd:%d\n",_sockfd);
        
        struct sockaddr_in local;//创建
        bzero(&local,sizeof(local));//开辟
        //填充sock_addr_in的内容
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        //此时前面的操作都在用户栈上还没有进OS，所以要进行bind，bind之后才进OS
        //绑定bind
        int n = bind(_sockfd,(struct sockaddr *)&local,sizeof(local));
        if(n<0)//bind失败
        {
            LOG(FATAL,"bind error ,%s,%d\n",strerror(errno),errno);
            exit(BIND_ERROR);
        }

        //bind成功
        LOG(INFO,"bind success socket\n");


        
    }
    void Start()
    {
        _isrunning = true;
        while(true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);//收到的
            if(n>0)//有收到
            {
                buffer[n]=0;
                InetAddr addr(peer);
                LOG(DEBUG,"get message from[%s:%d]:%s\n",addr.Ip().c_str(),addr.Port(),buffer);

                sendto(_sockfd,buffer,strlen(buffer),0,(struct sockaddr *)&peer,len);//发回去

            }
        }
        _isrunning = false;
    }

    //析构
    ~UdpServer()
    {}

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
};